import React, { act } from 'react';
import { render, screen, fireEvent } from '@testing-library/react';
import '@testing-library/jest-dom';
import PdfAnnotationPage from '../PdfAnnotationPage';

// Mock PdfViewer component
jest.mock('../../components/PdfViewer', () => {
  return function MockPdfViewer(props) {
    return (
      <div
        data-testid="mock-pdf-viewer"
        data-tool={props.selectedTool}
      >
        Mock PDF Viewer
      </div>
    );
  };
});

// Mock AnnotationToolbar component
jest.mock('../../components/AnnotationToolbar', () => {
  return function MockAnnotationToolbar(props) {
    return (
      <div data-testid="mock-annotation-toolbar">
        <button onClick={() => props.onToolSelect('rectangle')}>Rectangle Tool</button>
        <button onClick={() => props.onToolSelect('mouse')}>Mouse Tool</button>
        <button onClick={() => props.onToolSelect('eraser')}>Eraser Tool</button>
      </div>
    );
  };
});

describe('PdfAnnotationPage', () => {
  beforeEach(() => {
    // Reset all mocks before each test
    jest.clearAllMocks();
  });

  it('renders initial state correctly', async () => {
    await act(async () => {
      render(<PdfAnnotationPage />);
    });

    // Check if toolbar section is rendered
    expect(screen.getByText('标注工具')).toBeInTheDocument();
    expect(screen.getByText('文件上传')).toBeInTheDocument();
    expect(screen.getByText('选择PDF文件')).toBeInTheDocument();
  });

  it('handles file upload', async () => {
    await act(async () => {
      render(<PdfAnnotationPage />);
    });

    const file = new File(['test'], 'test.pdf', { type: 'application/pdf' });
    const input = screen.getByLabelText('选择PDF文件');

    await act(async () => {
      fireEvent.change(input, { target: { files: [file] } });
    });

    expect(screen.getByTestId('mock-pdf-viewer')).toBeInTheDocument();
  });

  it('shows error for non-PDF files', async () => {
    const mockAlert = jest.spyOn(window, 'alert').mockImplementation(() => {});
    
    await act(async () => {
      render(<PdfAnnotationPage />);
    });

    const file = new File(['test'], 'test.txt', { type: 'text/plain' });
    const input = screen.getByLabelText('选择PDF文件');

    await act(async () => {
      fireEvent.change(input, { target: { files: [file] } });
    });

    expect(mockAlert).toHaveBeenCalledWith('请上传PDF文件！');
    mockAlert.mockRestore();
  });

  it('handles tool selection', async () => {
    await act(async () => {
      render(<PdfAnnotationPage />);
    });

    const file = new File(['test'], 'test.pdf', { type: 'application/pdf' });
    const input = screen.getByLabelText('选择PDF文件');

    await act(async () => {
      fireEvent.change(input, { target: { files: [file] } });
    });

    const mouseToolButton = screen.getByText('Mouse Tool');
    await act(async () => {
      fireEvent.click(mouseToolButton);
    });

    expect(screen.getByTestId('mock-pdf-viewer')).toHaveAttribute('data-tool', 'mouse');
  });
}); 